package com.bootdo.wx.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.bootdo.wx.domain.Config;
import com.bootdo.wx.domain.WechatMenu;
import com.bootdo.wx.service.ConfigService;
import com.bootdo.wx.service.WechatMenuService;
import com.front.web.wx.utils.TokenUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.HttpUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;

/**
 * 
 * 
 * @author haojiangbo
 * @email 2100272728@qq.com
 * @date 2018-11-21 14:23:10
 */
 
@Controller
@RequestMapping("/wx/wechatMenu")
public class WechatMenuController extends BaseController{
	@Autowired
	private WechatMenuService wechatMenuService;
	@Autowired
	private ConfigService configService;
	//insert into sys_menu(parent_id,name,url,perms,type)  values (3,'微信菜单','/wx/wechatMenu','wx:wechatMenu:wechatMenu',1)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (144,'添加','/wx/wechatMenu/add','wx:wechatMenu:add',2)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (144,'修改','','wx:wechatMenu:edit',2)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (144,'删除','/wx/wechatMenu/remove','wx:wechatMenu:remove',2)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (144,'批量删除','/wx/wechatMenu/batchRemove','wx:wechatMenu:batchRemove',2)
	//type 0是分类菜单 1是小菜但 2是按钮

	@ModelAttribute
	public WechatMenu get(@RequestParam(required=false) Integer id) {
		if (id != null){
			return wechatMenuService.get(id);
		}else{
			return new WechatMenu();
		}
	}

	@PostMapping("/getById")
	@ResponseBody
	R getById(WechatMenu wechatMenu) {
		return R.ok().put("i",wechatMenu);
	}

	@GetMapping()
	@RequiresPermissions("wx:wechatMenu:wechatMenu")	
	String WechatMenu(){
	    return "wx/wechatMenu/wechatMenu";
	}
	
	@ResponseBody
	@PostMapping("/list")
	@RequiresPermissions("wx:wechatMenu:wechatMenu")
	public List<WechatMenu>  list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<WechatMenu> wechatMenuList = wechatMenuService.list(query);
		int total = wechatMenuService.count(query);
		PageUtils pageUtils = new PageUtils(wechatMenuList, total);
		return wechatMenuList;
	}


	@ResponseBody
	@PostMapping("/treelist")
	@RequiresPermissions("wx:wechatMenu:wechatMenu")
	public R treelist(@RequestParam Map<String, Object> params){
		//查询列表数据
		params.put("parentId", 0);
		List<WechatMenu> wechatMenuList = wechatMenuService.list(params);
		hasChild(wechatMenuList);
		return R.ok().put("l", wechatMenuList);
	}

	void hasChild(List<WechatMenu> wechatMenuList ){
		wechatMenuList.stream().forEach(wechatMenu ->{
			Map map = new HashMap();
			map.put("parentId",wechatMenu.getId());
			List<WechatMenu> wechatMenuList2  = wechatMenuService.list(map);
			if(null != wechatMenuList2 && wechatMenuList2.size() > 0){
				wechatMenu.setChildren(wechatMenuList2);
				wechatMenu.setHasChildren(true);
				hasChild(wechatMenuList2);
			}
		});
	}


	@GetMapping("/add")
	@RequiresPermissions("wx:wechatMenu:edit")
	String add(HttpServletRequest request){
		String t = request.getParameter("parentId");
		WechatMenu wechatMenu = new WechatMenu();
		if(!StringUtils.isEmpty(t)) {
			 wechatMenu = wechatMenuService.get(Integer.parseInt(t));
			
		}
		 request.setAttribute("menu", wechatMenu);
	    return "wx/wechatMenu/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wx:wechatMenu:edit")
	String edit(@PathVariable("id") Integer id,Model model){
		WechatMenu wechatMenu = wechatMenuService.get(id);
		model.addAttribute("wechatMenu", wechatMenu);
	    return "wx/wechatMenu/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wx:wechatMenu:edit")
	public R save( WechatMenu wechatMenu){
		wechatMenu.setUserId(getUserId().intValue());
		if(null != wechatMenu.getParentId() && !wechatMenu.getParentId().equals(0)) {
			wechatMenu.setParentName(wechatMenuService.get(wechatMenu.getParentId()).getName());
		}
		if(wechatMenuService.save(wechatMenu)>0){
			return R.ok();
		}
		return R.error();
	}
	
	
	
	/**
	  * 生成微信菜单
	 * @throws Exception 
	 */
	@ResponseBody
	@PostMapping("/createWxMenu")
	@RequiresPermissions("wx:wechatMenu:edit")
	public R createWxMenu(HttpServletRequest request) throws Exception{
		JSONObject j = new JSONObject();
		Map m =  new HashMap();
		m.put("parentId", 0);
		m.put("userId", getUserId());
		List<WechatMenu> l = wechatMenuService.list(m);
		if(null != l && l.size() > 0) {
			j.put("button", gMenu(l));
		}
		System.err.println(j.toJSONString());
		Config c =  configService.getByUserId(getUserId());
		String r =  HttpUtil.doPost("https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+TokenUtils.getToken(c), j.toJSONString());
		System.err.println("r = > " + r);
	
		return R.ok();
	}
	
	
	private JSONArray gMenu(List<WechatMenu> l) {
	   JSONArray array  = new JSONArray();
	   if(null != l) {
		   for(int i = 0; i < l.size(); i++) {	  
			   JSONObject j1 = new JSONObject();
			   j1.put("name", l.get(i).getName());
			   j1.put("type", l.get(i).getType());
			   if(l.get(i).getType().equals("view")) {
				   j1.put("url", l.get(i).getUrl());
			   }else {
				   j1.put("key", l.get(i).getEventKey());
			   }	   
			   Map m = new HashMap();
			   m.put("parentId", l.get(i).getId());
			   List<WechatMenu> l2 =  wechatMenuService.list(m);
			   if(null != l2 && l2.size() > 0) {
				   j1.put("sub_button", gMenu(l2));
			   }
			   array.add(j1);
		   }
	   }	   
	   return array;
	}
	
	
	
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wx:wechatMenu:edit")
	public R update( WechatMenu wechatMenu){
		wechatMenuService.update(wechatMenu);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wx:wechatMenu:edit")
	public R remove( Integer id){
		if(wechatMenuService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wx:wechatMenu:edit")
	public R remove(@RequestParam("ids[]") Integer[] ids){
		wechatMenuService.batchRemove(ids);
		return R.ok();
	}
	
}